package io.keyss.view_record.utils

import android.app.Activity
import android.content.ContentValues
import android.media.MediaScannerConnection
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.annotation.RequiresApi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

/**
 * Description:
 *
 * Time: 2023/11/21 21:17
 * @author Key
 */
object FrameUtil {
    //H264 IDR
    @RequiresApi(Build.VERSION_CODES.Q)
    fun saveLocalFileToPublicDir(
        activity: Activity,
        sourcePath: String, // ← 本地文件路径
        mimeType: String,
        fileName: String,
    ) {
        val isNeedPermission = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q



        CoroutineScope(Dispatchers.IO).launch {
            try {
                val inputFile = File(sourcePath)
                if (!inputFile.exists()) {
                    Log.e("saveLocalFile", "文件不存在：$sourcePath")
                    return@launch
                }

                FileInputStream(inputFile).use { inputStream ->
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        val contentValues = ContentValues().apply {
                            put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
                            put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
                            put(
                                MediaStore.MediaColumns.RELATIVE_PATH, when {
                                    mimeType.startsWith("image/") -> Environment.DIRECTORY_PICTURES
                                    mimeType.startsWith("video/") -> Environment.DIRECTORY_MOVIES
                                    else -> Environment.DIRECTORY_DOWNLOADS
                                }
                            )
                        }

                        val uri = activity.contentResolver.insert(
                            when {
                                mimeType.startsWith("image/") -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                                mimeType.startsWith("video/") -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                                else -> MediaStore.Downloads.EXTERNAL_CONTENT_URI
                            }, contentValues
                        )

                        uri?.let {
                            activity.contentResolver.openOutputStream(it)?.use { outputStream ->
                                inputStream.copyTo(outputStream)
                            }
                        }

                    } else {
                        val directory = when {
                            mimeType.startsWith("image/") -> Environment.DIRECTORY_PICTURES
                            mimeType.startsWith("video/") -> Environment.DIRECTORY_MOVIES
                            else -> Environment.DIRECTORY_DOWNLOADS
                        }

                        val dirFile = Environment.getExternalStoragePublicDirectory(directory)
                        if (!dirFile.exists()) dirFile.mkdirs()
                        val file = File(dirFile, fileName)

                        FileOutputStream(file).use { outputStream ->
                            inputStream.copyTo(outputStream)
                        }

                        MediaScannerConnection.scanFile(
                            activity, arrayOf(file.absolutePath), arrayOf(mimeType), null
                        )
                    }
                }

            } catch (e: Exception) {
                Log.e("saveLocalFile", "保存失败: ${e.message}", e)
            }
        }
    }

}
